package com.putao.album.user;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.child.ActivityChildAdd;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.main.AlbumHomeActivity;
import com.putao.album.user.util.FlowType;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.SharedPreferencesHelper;
import com.putao.album.util.StringHelper;
import com.putao.album.util.UmengTouchEvent;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/22.
 */
public class ActivityInputPassword extends BaseActivity {
    private TextView txt_mobile_display;
    Button btn_next, btn_show_pwd, btn_forget_pwd, btn_back;
    private EditText etx_pwd;
    boolean mShowPwd = false;
    private String telnum;
    private int mflowtype = 0;
    private String mPassword;

    @Override
    public int doGetContentViewId() {
        return R.layout.activity_input_password;
    }

    @Override
    public void doInitSubViews(View view) {
        txt_mobile_display = queryViewById(R.id.txt_mobile_display);
        btn_next = queryViewById(R.id.btn_next);
        btn_show_pwd = queryViewById(R.id.btn_show_pwd);
        etx_pwd = queryViewById(R.id.etx_pwd);
        btn_forget_pwd = queryViewById(R.id.btn_forget_pwd);
        btn_back = queryViewById(R.id.btn_back);
        addOnClickListener(btn_next, btn_show_pwd, btn_forget_pwd, btn_back);
        displayPassword();
        etx_pwd.addTextChangedListener(mPwdTextWatch);
    }

    TextWatcher mPwdTextWatch = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String pwd = etx_pwd.getText().toString();
            if (!StringHelper.isEmpty(pwd)) {
                btn_next.setEnabled(true);
                btn_next.setAlpha(1f);
            } else {
                btn_next.setEnabled(false);
                btn_next.setAlpha(0.5f);
            }
        }
    };

    @Override
    public void doInitData() {
        if (getIntent() != null) {
            Bundle receiveBundle = getIntent().getExtras();
            if (receiveBundle != null) {
                telnum = receiveBundle.getString(FlowType.flag_mobile);
                mflowtype = receiveBundle.getInt(FlowType.flag_flowtype, 0);
            }
        }
        txt_mobile_display.setText(telnum);
        btn_next.setText(getResources().getString((mflowtype == FlowType.flow_login) ? R.string.user_login : R.string.finished));
        btn_forget_pwd.setVisibility((mflowtype == FlowType.flow_login) ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                next();
                break;
            case R.id.btn_show_pwd:
                mShowPwd = !mShowPwd;
                displayPassword();
                break;
            case R.id.btn_forget_pwd:
                MobclickAgent.onEvent(mContext, UmengTouchEvent.CLICK_PASSWORD);
                Bundle bundle = new Bundle();
                bundle.putString(FlowType.flag_mobile, telnum);
                bundle.putInt(FlowType.flag_flowtype, FlowType.flow_modify_pwd);
                ActivityHelper.startActivity(mActivity, ActivityInputVCode.class, bundle);
                finish();
                break;
            case R.id.btn_back:
                finish();
                break;
        }
    }

    void next() {
        mPassword = etx_pwd.getText().toString();
        if (StringHelper.isEmpty(mPassword)) {
            showToast("请输入密码");
            return;
        }
        switch (mflowtype) {
            case FlowType.flow_login:
                login();
                break;
            case FlowType.flow_modify_pwd:
                modifypwd();
                break;
            case FlowType.flow_register:
                register();
                break;
        }
    }

    /**
     * 用户注册
     */
    void register() {
        if (mPassword.length() < 6) {
            showToast("密码不能少于6位");
            return;
        }
        if (mPassword.length() > 18) {
            showToast("密码不能多于18位");
            return;
        }
        MobclickAgent.onEvent(mContext, UmengTouchEvent.CLICK_REGISTER);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", telnum);
        params.put("password", mPassword);
        params.put("confirmpassword", mPassword);
        params.put("nickname", "");
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_REGISTER, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {//注册成功
                        doAnalysisSuccessResponse(response);
                        callback();
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    /**
     * 注册成功后回调
     */
    void callback() {
        RequestParams params = new RequestParams(HttpRequestUtil.buildHttpRequestParams(new HashMap()));
        params.put("umeng_device_token", CommonUtils.getUmengDeviceToken());
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_REGISTER_SUCESS_CALLBACK, params, null);
    }

    /**
     * 登录
     */
    void login() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", telnum);
        params.put("password", mPassword);
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_LOGIN, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {//登录成功
                        doAnalysisSuccessResponse(response);
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    /**
     * 重置密码
     */
    void modifypwd() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", telnum);
        params.put("password", mPassword);
        params.put("confirmpassword", mPassword);
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_RESET_PASSWD, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {//密码重置成功
                        doAnalysisSuccessResponse(response);
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    void doAnalysisSuccessResponse(String response) {
        try {
            JSONObject json = new JSONObject(response);
            if (json != null) {
                JSONObject data = json.getJSONObject("data");
                if (data != null) {
                    saveUserInfo(data);
                    EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_LOGIN_SUCCESS));
                    finish();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (mflowtype == FlowType.flow_register) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isRegister", true);
            ActivityHelper.startActivity(mActivity, ActivityChildAdd.class, bundle);
        } else {
            ActivityHelper.startActivity(mActivity, AlbumHomeActivity.class);
        }
    }

    private void saveUserInfo(JSONObject data) {
        String token = data.optString("token");
        String uid = data.optString("uid");
        String nickname = data.optString("nickname");
        Loger.d("uid->" + uid);
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_UID, uid);
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_MOBILE, telnum);
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_NICKNAME, nickname);
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_TOKEN, token);
        SharedPreferencesHelper.saveStringValue(mContext, PuTaoConstants.PREFERENCE_KEY_PASSWORD, mPassword);
    }


    void displayPassword() {
        btn_show_pwd.setBackgroundResource(mShowPwd ? R.drawable.btn_show_pwd : R.drawable.btn_hide_pwd);
        etx_pwd.setTransformationMethod(mShowPwd ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        etx_pwd.setSelection(etx_pwd.getText().toString().length());
    }
}
